package com.hq.ims.data.quartz.service;


import com.hq.ims.data.quartz.utils.QuartzUtils;
import com.hq.ims.data.vo.quartz.QuartzJobInfo;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Scheduler;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class QuartzServiceImpl implements QuartzService {

    @Resource
    private SchedulerFactoryBean schedulerFactoryBean;

    @Override
    public void addJob(QuartzJobInfo info) {
        //保证参数不为空
        if (info != null) {
            QuartzUtils.addJob(schedulerFactoryBean.getScheduler(), info.getJobName(), info.getCls(), info, info.getCronStr());
            log.info("添加" + info.getJobName() + "定时任务成功！");
        }
    }

    @Override
    public void removeJob(String jobName) {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        //删除定时任务
        QuartzUtils.removeJob(scheduler, jobName);
        log.info("删除" + jobName + "定时任务成功！");
    }

    public void modifyJobTime(String jobName, LocalDateTime fireDate) {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        String cron = QuartzUtils.getCronStr(fireDate);
        //修改定时任务
        QuartzUtils.modifyJobTime(scheduler, jobName, cron);
        System.out.println("修改" + jobName + "定时任务成功！");
    }
}
